package com.example.education.controller;

import com.example.education.exception.ParamException;
import com.example.education.model.User;
import com.example.education.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/interface/user")
public class UserController {

    @Autowired
    UserService userService;

    @RequestMapping(value = "/login",method = RequestMethod.POST)
    public String  login(String loginName, String password, Model model, HttpSession session){
        User user = new User();
        try {
            user = userService.login(loginName, password);
            if (user != null) {
                session.setAttribute("user",user);
                model.addAttribute("user",user);
            } else {
                return "login";
            }
        } catch (ParamException e) {
            e.printStackTrace();
        }
        if(user.getUserCate()==1){
            return "home";
        }else if(user.getUserCate()==2){
            return "index";
        }else {
            return "login";
        }

    }

    @RequestMapping(value = "/register",method = RequestMethod.POST)
    public String  register(String loginName,String password) {
        try {
            userService.register(loginName, password);
        } catch (ParamException e) {
            e.printStackTrace();
        }
        return "home";
    }

    @RequestMapping("/update")
    public boolean updateUserInfo(User user){
        boolean result = false;
        try {
            result = userService.updateUserInfo(user);
        } catch (ParamException e) {
            e.printStackTrace();
        }
        return result;
    }

    @RequestMapping("/getById")
    public User getUserById(Integer id){
        User user = new User();
        try {
            user = userService.getUserById(id);
        } catch (ParamException e) {
            e.printStackTrace();
        }
        return user;
    }

    @RequestMapping("/getByIds")
    public List<User> getUserByIds(List<Integer> ids){
        List<User> users = new ArrayList<>();
        try {
            users = userService.getUserByIds(ids);
        } catch (ParamException e) {
            e.printStackTrace();
        }
        return users;
    }
}
